///////////////////////////////////////////////////////////////////////////////
//  Copyright (C) 2010 Taesun Moon, The University of Texas at Austin
// 
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 3 of the License, or (at your option) any later version.
// 
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
// 
//  You should have received a copy of the GNU Lesser General Public
//  License along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package tikka.utils.math;

/**
 * Calculates the perplexity
 *
 * @author tsmoon
 */
public class PerplexityEval extends SampleEval {

    /**
     * Calculates the perplexity. Given an array of log probabilities (over tokens),
     * returns the geometric mean.
     *
     * @param logprobs Array of log probabilities
     * @param tokens The number of tokens involved in creating the log logprobs
     * @return the harmonic mean
     */
    @Override
    public double average(double[] logprobs, int tokens) {
        double ave = 0;
        for (int i = 0; i < logprobs.length; ++i) {
            ave += 1 / Math.exp(0 - logprobs[i] / tokens);
        }
        ave = logprobs.length / ave;
        return ave;
    }
}
